local RoomBase = require 'packages.wenhe_yanbing.wenhe_yanbing.core.roombase'
local ClientPlayer = require "packages.wenhe_yanbing.wenhe_yanbing.client.clientplayer"

---@class WenheYanbing.Client: WenheYanbing.RoomBase, ClientBase
local Client = RoomBase:subclass("WenheYanbing.Client")
Client:include(Fk.Base.ClientBase)

function Client:initialize(_client)
    RoomBase.initialize(self)
    Fk.Base.ClientBase.initialize(self, _client)

    self.clientplayer_klass = ClientPlayer
    
    -- 确保 callbacks 存在
    if not self.callbacks then
        self.callbacks = {}
    end
    
    -- 注册回调 - 使用正确的方法名
    self:addCallback("UpdatePhase", self.handleUpdatePhase)
    self:addCallback("RecruitPhase", self.handleRecruitPhase)
    self:addCallback("CombatPhase", self.handleCombatPhase)
    self:addCallback("CombatResult", self.handleCombatResult)
    self:addCallback("PlayerEliminated", self.handlePlayerEliminated)
    self:addCallback("EnterRecruit", self.handleEnterRecruit)
end

-- 创建安全的游戏数据
function Client:createSafeGameData(data)
    local safeData = {}
    
    -- 基础游戏状态 - 确保是简单值
    if data.phase then
        safeData.phase = tostring(data.phase)
    else
        safeData.phase = tostring(self.phase or "unknown")
    end
    
    if data.turn then
        safeData.turn = tonumber(data.turn) or 0
    else
        safeData.turn = tonumber(self.turn) or 0
    end
    
    -- 玩家数据 - 确保是简单数据或安全的表
    if data.currentPlayer and self:isValueSafe(data.currentPlayer) then
        safeData.currentPlayer = data.currentPlayer
    elseif self.current and self:isValueSafe(self.current) then
        safeData.currentPlayer = self.current
    end
    
    -- 其他数据 - 逐一验证
    local safeFields = {
        "players", "combatLog", "opponent", "damageTaken", "playerEliminated"
    }
    
    for _, field in ipairs(safeFields) do
        if data[field] and self:isValueSafe(data[field]) then
            safeData[field] = data[field]
        end
    end
    
    return safeData
end

-- 检查值是否安全（可序列化）
function Client:isValueSafe(value)
    local valueType = type(value)
    
    -- 允许的基本类型
    if valueType == "string" or valueType == "number" or valueType == "boolean" then
        return true
    end
    
    -- 允许nil
    if valueType == "nil" then
        return true
    end
    
    -- 检查表是否安全
    if valueType == "table" then
        return self:isTableSafe(value)
    end
    
    -- 不允许其他类型（function, userdata, thread等）
    return false
end

-- 检查表是否安全
function Client:isTableSafe(tbl, visited)
    visited = visited or {}
    
    -- 防止循环引用
    if visited[tbl] then
        return false
    end
    visited[tbl] = true
    
    for k, v in pairs(tbl) do
        -- 检查键是否安全
        local keyType = type(k)
        if keyType ~= "string" and keyType ~= "number" then
            return false
        end
        
        -- 检查值是否安全
        if not self:isValueSafe(v) then
            return false
        end
        
        -- 递归检查嵌套表
        if type(v) == "table" then
            if not self:isTableSafe(v, visited) then
                return false
            end
        end
    end
    
    return true
end

function Client:handleUpdatePhase(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self.phase = data.phase or self.phase
    self.turn = data.turn or self.turn
    
    self:sendDataToUI({
        phase = self.phase,
        turn = self.turn
    })
end

function Client:handleRecruitPhase(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self.phase = "recruit"
    self.turn = data.turn or self.turn
    
    self:sendDataToUI({
        phase = "recruit",
        turn = self.turn,
        players = data.players or self.players
    })
end

function Client:handleCombatPhase(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self.phase = "combat"
    self.turn = data.turn or self.turn
    
    self:sendDataToUI({
        phase = "combat",
        turn = self.turn
    })
end

function Client:handleCombatResult(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self:sendDataToUI({
        combatLog = data.log or {},
        opponent = data.opponent,
        damageTaken = data.damageTaken or 0
    })
end

function Client:handlePlayerEliminated(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self:sendDataToUI({
        playerEliminated = data
    })
end

function Client:handleEnterRecruit(data)
    -- 验证数据
    if not data or type(data) ~= "table" then
        data = {}
    end
    
    self.phase = "recruit"
    
    self:sendDataToUI({
        phase = "recruit",
        currentPlayer = data
    })
end

-- 发送数据到UI
function Client:sendDataToUI(data)
    -- 验证输入数据
    if not data or type(data) ~= "table" then
        print("Warning: Invalid data passed to sendDataToUI")
        data = {}
    end
    
    -- 创建安全的数据表
    local gameData = self:createSafeGameData(data)
    
    -- 验证最终数据
    if not self:isTableSafe(gameData) then
        print("Error: gameData contains unsafe data structure")
        gameData = { 
            phase = "error", 
            turn = 0,
            message = "Data structure error" 
        }
    end
    
    -- 通知UI更新
    self:notifyUI("UpdateGameData", gameData)
end

return Client